package com.easylinkin.linkappapi.taskscheduler.job;

import com.easylinkin.linkappapi.common.utils.DateUtil;
import com.easylinkin.linkappapi.taskscheduler.entity.JobEntity;
import java.io.Serializable;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>定时任务测试类 没有用</p>
 *
 * @author TongJie
 * @since 2020/6/5 18:03
 */
@Service
public class ApiJob implements Job, Serializable {

    public static Logger LOGGER = LoggerFactory.getLogger(ApiJob.class);

    @Autowired
    private Scheduler scheduler;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void execute(JobExecutionContext context) throws JobExecutionException {
        // 取得job详情
        JobDetail jobDetail = context.getJobDetail();
        // 取得job名称
        String jobName = jobDetail.getKey().getName();
        String jobgroup = jobDetail.getKey().getGroup();
        LOGGER.info("=========定时任务 |  任务分组：" + jobgroup + "，任务名称：" + jobName + "，调用接口服务执行开始=========");
        LOGGER.info("定时任务名称: " + jobName);
        // 取得job的类
        LOGGER.info("定时任务执行类名: " + jobDetail.getJobClass());
        // 取得jobgroup名称
        LOGGER.info("任务组名: " + jobgroup);
        // 取得job开始时间
        LOGGER.info(jobName + " 开始时间： " + DateUtil.format(context.getFireTime(), "yyyy-MM-dd HH:mm:ss"));
        // 取得job下次触发时间
        LOGGER.info("下次执行时间： " + DateUtil.format(context.getNextFireTime(), "yyyy-MM-dd HH:mm:ss"));
        JobDataMap dataMap = jobDetail.getJobDataMap();
        String jobtasktype = dataMap.getString("jobtasktype");
        String jobtype = dataMap.getString("jobtype");
        String apiurl = dataMap.getString("apiurl");
        String params = dataMap.getString("params");
        LOGGER.info("jobtasktype: " + jobtasktype);
        LOGGER.info("jobtype: " + jobtype);
        LOGGER.info("apiurl: " + apiurl);
        LOGGER.info("params: " + params);
        String result = "";
        LOGGER.info("定时任务接口调用返回结果：" + result);
        /*
         * 1.判断如果为一次性执行，则执行后，将job状态置为禁用，并移除任务
         */
        if ("1".equals(jobtype) && null != context.getNextFireTime()) {
            JobEntity job = new JobEntity();
            job.setJobName(jobName);
            job.setJobGroup(jobgroup);
            job.setJobStatus("0");
            int success = 0;
            if (success <= 0) {
                LOGGER.error("任务组：" + jobgroup + ",任务名称：" + jobName + "，移除任务错误{}", job.toString());
                throw new JobExecutionException("移除任务失败");
            }
            try {
                TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobgroup);
                // 停止触发器
                scheduler.pauseTrigger(triggerKey);
                // 移除触发器
                scheduler.unscheduleJob(triggerKey);
                // 删除任务
                scheduler.deleteJob(JobKey.jobKey(jobName, jobgroup));
                LOGGER.info("移除任务：" + JobKey.jobKey(jobName));
            } catch (Exception e) {
                LOGGER.info("任务组：" + jobgroup + ",任务名称：" + jobName + "，执行移除任务失败");
                throw new JobExecutionException("移除任务失败");
            }
        }
        LOGGER.info("=========定时任务 |  任务分组：" + jobgroup + "，任务名称：" + jobName + "，调用接口服务执行结束=========");
    }
}
